<script setup lang="jsx">
  import {watch,inject,ref,nextTick,reactive,computed,provide} from 'vue'
import waybillTask from '@/api/abroad/waybillTask'
import { Message, Modal } from '@arco-design/web-vue'
import trayList from "@/views/abroad/waybillTask/components/trayList.vue";
import dicthelpApi from "@/api/dicthelpApi.js";
import {getDictData} from "@/utils/crud/dictNew.js";
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";
import fileType from "@/views/components/fileType.vue";
import uploadConfig from '@/config/upload'
import tool from '@/utils/tool'
const columnsDist = inject('columnsDist')
const span=ref(6)
const crudRef = ref()
const formRef=ref(null)
const trayListRef=ref()
const selected=ref([])
const currentStatus =ref('1')
const filetypeRef=ref()

// 表单数据
const rules = {
      task_type: [{ required: true, message:'请选择指令类型',validateTrigger: 'blur'}, ],
      depot_id: [{ required: true, message:'请选择仓库',validateTrigger: 'blur'}, ],
      title: [{ required: true, message:'请输入标题',validateTrigger: 'blur'}, ],
      remark: [{ required: true, message:'请输入描述',validateTrigger: 'blur'}, ],
      // car_id: [{ required: true, message:'请选择车辆',validateTrigger: 'blur'}, ],
    }
const shipmentList=ref([])
//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
//行数选中
const setSelecteds = (key) => {
  selected.value = key
  console.log('selected.value',key)
}
const formData = ref({
  id:'',
  task_type: "", 
  depot_id: "", 
  urgent: "1", 
  title: "", 
  remark: "", 
  status:0,
  shipments: [],
  files:[]
})
const visible = ref(false)
 const addTrayList = () => {
  trayListRef.value.open()    
  }
  
  const downloadAdd=()=>{
  filetypeRef.value.onShow();
}
//上传文件
const addFileTap=(data)=>{
  data.fileList.forEach(item => {
    item.response.data.attachable_type=data.type
    upload.fileList.push(item.response.data)
    })
}
//下载上传文件
const downloadFile = (item) => {
  let url=''
  if(item?.info){
    url=uploadConfig.storage.OSS+item.info.url
  }else{
    url=uploadConfig.storage.OSS+item.url

  }
  window.location.href=url
}
//删除上传文件
const deleteDownload = (index) => {
  upload.fileList.splice(index, 1)
}

//删除tabel
const deleteAction=(index)=>{
  // formData.value.trays.splice(index,1)
  shipmentList.value.splice(index,1)
}
    //tabel类型发生改变
    const serviceTypeChang=(e,index,type)=>{
      dicthelpApi.addressChang(e).then(res => {
        if(!type){
          shipmentList.value[index].address_id=''
          if(res.data.length==1){
            shipmentList.value[index].address_id=res.data[0].value
          }
        }
        shipmentList.value[index].addressList=res.data
    })    
    }
const columns = ref([
  {title: '库内任务', dataIndex: 'is_intercept',slotName: 'is_intercept',width: 60,align:'center',type:'select',required:true,},
  {title: '服务类型', dataIndex: 'send_type',slotName: 'send_type',align:'center',titleSlotName: 'customAgeTitle',type:'select',required:true,},
  {title: '派送类型', dataIndex: 'service_type_id',slotName: 'service_type_id',align:'center',titleSlotName: 'customAgeTitle',type:'select',required:true,},
  {title: '目的地', dataIndex: 'address_id',slotName: 'address_id',titleSlotName: 'customAgeTitle',required:true,align:'center', },
  {title: '箱唛', dataIndex: 'shipment_no',align:'center',},
  {title: 'CTNS', dataIndex: 'parcel_count_estimate',slotName: 'parcel_count_estimate',titleSlotName: 'customAgeTitle',type:'input',required:true,align:'center',},
  {title: 'Weight', dataIndex: 'weight',slotName: 'weight',type:'input',titleSlotName: 'customAgeTitle',required:true,align:'center',},
  {title: 'CBM', dataIndex: 'volume',slotName: 'volume',type:'input',titleSlotName: 'customAgeTitle',required:true,align:'center',},
  {title: 'ID', dataIndex: 'fba_id',slotName: 'fba_id',type:'input',required:true,align:'center',},
  {title: 'PO', dataIndex: 'po_number',slotName: 'po_number',type:'input',align:'center',},
  {title: '操作', slotName: 'fixed',fixed: 'right',width: 60,align:'center',},

])
const columnsCls=()=>{
  if(formData.value.status==2 || formData.value.status==3){
  return columns.value
  }else{
    let columnsData=columns.value.filter(item=>item.dataIndex != 'is_intercept')
  return columnsData
  }
}
//选择的托盘并去重
const tableListPrant=(data)=>{
  console.log('data',data)
  formData.value.shipments=[]
  let shipments=shipmentList.value
  let newTrays=shipments.concat(data)
  let list=[]
  let uninewTrays=newTrays.filter((item) => !list.includes(item.idsi) && list.push(item.idsi))
  // uninewTrays.map((item,index)=>{
  //   formData.value.shipments.push(item.id)
  // })
  shipmentList.value=uninewTrays
  shipmentList.value.map((item,index)=>{
    if(item.send_type==0 || item.send_type==null){
      item.send_type=null
    }else{
      item.send_type=item.send_type.toString()
    }  
    item.service_type_id=Number(item.service_type_id)
    serviceTypeChang(item.service_type_id,index,'init')
  })
}
 //详情
 const tableList=()=>{
  waybillTask.read(formData.value.id).then(res => {
        formData.value=res.data
        formData.value.task_type=res.data.task_type.toString()
        formData.value.urgent=res.data.urgent.toString()
        shipmentList.value=res.data.list
        upload.fileList=res.data.files
        buttonGroups[1].form.form.task_id=formData.value.id
        // console.log('buttonGroups',buttonGroups)
        // formData.value.files=res.data.file
        // res.data.file.map((item,index)=>{
        //   item.name=item.filename
        // })
        // upload.fileList=res.data.file
        // waybillServiceShipmentTypeListData()
        shipmentList.value.map((item,index)=>{
          if(item.send_type==0){
            item.send_type=null
          }else{
            item.send_type=item.send_type.toString()
          } 
          item.service_type_id=Number(item.service_type_id)
          serviceTypeChang(item.service_type_id,index,'init')
        })
      })
     
    }
  const onShow = async (value) => {
    visible.value = true
     //编辑
     if(value){
      formData.value.id=value.id
      tableList() 
    }
  }


/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
//   open: false,
  // 弹出层标题（用户导入）
  title: "",
  fileList:[],
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + tool.getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_URL + "/system/uploadFile"
});

const emits = defineEmits(['addClick','emitClick'])
  //新增 //编辑
  const handleBeforeOk =async (formEl) => {
    // return false
      let formParse = JSON.parse(JSON.stringify(formData.value)); // 深拷贝数据
      formParse.shipments=[]
      for(let i = 0 ; i <  shipmentList.value.length; i++){ 
          let item=shipmentList.value[i]
        if(item.send_type==0 || item.send_type==null){
              Message.error('服务类型必填')
              return;
        }
        if(!item.service_type_id){
              Message.error('派送类型必填')
              return;
        }
          if(!item.address_id){
                Message.error('目的地必填')
                return;
          }
          if(!item.parcel_count_estimate){
                Message.error('CTNS必填')
                return;
          }
          if(!item.weight){
                Message.error('Weight必填')
                return;
          }
          if(!item.volume){
                Message.error('CBM必填')
                return;
          }
          item.in_id=item.id
          formParse.shipments.push(item)
      }
      formParse.files=[]
      upload.fileList?.map((item, index) => {
        let obj={
          hash:item?.info?.hash || item?.hash,
          type:item.attachable_type
        }
        formParse.files.push(obj)
      })
        if(formParse.shipments.length==0){
            Message.error('请选择转运单')
            return false
        }
    if (!formEl) return
      await formEl.validate((valid) => {
        if (!valid) {
          if(formParse.id==''){
            waybillTask.save(formParse).then(res => {
              Message.success(res.message || `新增成功！`)
              emits('addClick');
              close()
            })
          }else{
            waybillTask.update(formParse).then(res => {
              Message.success(res.message || `编辑成功！`)
              emits('emitClick');
              close()
            })
          }
          
        }
      }) 
      
    };

    const buttonGroups = [
{
    title: '分配运单',
    api:waybillTask.AssignOutOrder,
    auth: ['sea:waybillTray:AssignOutOrder'],
    hideStatus: [null],
    form: {
          id: 'o_id',
          columns: [
            {
              title: '出库单', dataIndex: 'send_id', formType: 'select',
              rules: {required: true, message: "请选择出库单"},
              dict: {
                url: 'sea/waybillTaskSend/list',
                props: {label: 'title', value: 'id'},
                translation: true,
              },
            }
          ]
        }
  },
  {
    title: '完成库内任务',
    api:waybillTask.complete,
    auth: ['sea:waybillTask:complete'],
    hideStatus: [null],
    form: {
      id: 'o_id',
      form: {
        task_id: '',
      },
      columns: [
        {
          title: '出库单', dataIndex: 'send_id', formType: 'select',
          dict: {
            url: 'sea/waybillTaskSend/list',
            props: {label: 'title', value: 'id'},
            translation: true,
          },
        }
      ]
    }
  }
]
    const close = () => {
      formRef.value.resetFields();
      visible.value = false
      upload.fileList=[]
      formData.value.id=''
      formData.value.status=0
      formData.value.shipments=[]
      selected.value=[]
      shipmentList.value=[]
      
    }
const onBeforeCancel=()=>{
  Modal.confirm({
        title: '确认关闭?',
        onOk: () => {
          close()
        },
      });
}
defineExpose({ onShow })
provide('tableList',tableList);

</script>

<template>
  <a-drawer v-model:visible="visible" v-if="visible" width="80%" :onBeforeCancel="onBeforeCancel">
        <template #title>
          <div >{{  formData.id == "" ? '新增' : '编辑'}}</div>
          </template>
          <a-form ref="formRef" :rules="rules" :model="formData" auto-label-width >
            <div class="form-top-main">
              
            <a-col :span="span">
              <a-form-item field="task_type" label="指令类型" validate-trigger="change">
                <a-select v-model="formData.task_type" :options="columnsDist.dictObj.data.waybill_sea_task_shipment_out" :field-names="{ value: 'key', label: 'title' }"
                placeholder="请选择指令类型" allow-clear allow-search :virtual-list-props="{height:200}" /> 
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="depot_id" label="仓库" validate-trigger="change">
                <a-select v-model="formData.depot_id"  :options="columnsDist.dicthelpApi_depot.data" :field-names="{ value: 'id', label: 'name' }"
                placeholder="请选择仓库" allow-clear allow-search :virtual-list-props="{height:200}" /> 
              </a-form-item>
            </a-col>
            <!-- <a-col :span="span">
              <a-form-item field="car_id" label="车辆" validate-trigger="change">
                <a-select v-model="formData.car_id"
                placeholder="请选择车辆" allow-clear allow-search>
                <a-option v-for="item in columnsDist.dicthelpApi_waybillCarList.data" :value="item.id" :key="item.id">{{item.car_number}} - {{item.destination}}</a-option> 
              </a-select> 
              </a-form-item>
            </a-col> -->
            <a-col :span="span">
                <a-form-item field="size" label="紧急程度" >
                  <a-radio-group v-model="formData.urgent" type="radio">
                    <a-radio v-for="item in columnsDist.dictObj.data.waybill_sea_task_urgent" :value="item.key" :key="item.key">{{ item.title }}</a-radio>
                  </a-radio-group>
                </a-form-item>
            </a-col>



            <a-col :span="24">
              <a-form-item field="title" label="标题" validate-trigger="change">
                <a-input v-model="formData.title"  placeholder="请输入标题" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item field="remark" label="描述" validate-trigger="change">
                <a-textarea v-model="formData.remark"  placeholder="请输入描述" />
              </a-form-item>
            </a-col>         
          </div>
          <a-tabs default-active-key="1">
            
            <a-tab-pane key="1" title="运单">
              <div style="display: flex;align-items: center;margin: 10px 0;" v-if="formData.status<2">
                  <a-button type="primary" @click="addTrayList" style="margin-right: 10px;">               
                选择运单
              </a-button>
              </div>
              <div style="display: flex;align-items: center;margin: 10px 0;" v-else-if="formData.status==2 || formData.status==3">
                <button-group :button-groups="buttonGroups" :dataList="shipmentList" :crud-ref="crudRef" :selected="selected"
                :currentStatus="currentStatus"/>    
              </div>
              
              <a-table ref="tableRef" row-key="o_id" :columns="columnsCls()" :data="shipmentList" v-model:selectedKeys="selected" @selection-change="setSelecteds($event)" :row-selection="rowSelection" :bordered="false"  size="mini" column-resizable :pagination="false">
                <template #customAgeTitle="{column}">
                  <div>
                    <span style="color:red;">*</span>{{column.title}}
                  </div>
                </template>
                
                <template #is_intercept="{ record }">
                   {{ record.is_intercept == 1 ? '是' : '否' }}                
                  </template>
                <template #send_type="{ record }">
                  <a-select :options="columnsDist.dicthelpApi_waybillServiceTaskType.data" placeholder="请选择" :field-names="{ value: 'id', label: 'name' }" v-model="record.send_type" />

                    <!-- <a-select :options="columnsDist.dictObj.data.waybill_sea_task_shipment_operate" placeholder="请选择" :field-names="{ value: 'key', label: 'title' }" v-model="record.send_type" /> -->
                  </template>  
                <template #service_type_id="{ record,rowIndex }">
                    <a-select :options="columnsDist.dicthelpApi_waybillServiceShipmentTypeList.data" @change="serviceTypeChang($event,rowIndex)" placeholder="请选择" :field-names="{ value: 'id', label: 'name' }" v-model="record.service_type_id" />
                  </template>
                  <template #address_id="{ record }">
                    <a-select placeholder="请选择" v-model="record.address_id" >           
                    <a-option v-for="item in record.addressList" :key="item.value" :value="item.value">
                        {{item.label}}
                    </a-option>
                  </a-select>
                  </template>
                  <template #shipment_no="{ record }">
                    <a-input v-model="record.shipment_no" placeholder="请输入" />
                  </template>
                  <template #parcel_count_estimate="{ record }">
                    <a-input-number v-model="record.parcel_count_estimate" placeholder="请输入" :min="1"/>
                  </template>
                  <template #weight="{ record }">
                    <a-input-number  v-model="record.weight" placeholder="请输入" :min="0.01" :precision="2" :step="0.01"/>
                  </template>
                  <template #volume="{ record }">
                    <a-input-number v-model="record.volume" placeholder="请输入" :min="0.01" :precision="2" :step="0.01"/>
                  </template>
                  <template #tray_count_estimate="{ record }">
                    <a-input-number v-model="record.tray_count_estimate" placeholder="请输入" :min="1" />
                  </template>
                  <template #fba_id="{ record }">
                    <a-input v-model="record.fba_id" placeholder="请输入"/>
                  </template>
                  <template #po_number="{ record }">
                    <a-input v-model="record.po_number" placeholder="请输入" />
                  </template>
                  <template #remark="{ record }">
                    <a-input v-model="record.remark" placeholder="请输入" />
                  </template>
                  <template #fixed="{ record,rowIndex  }">
                    <a-link title="删除" @click="deleteAction(rowIndex)" v-if="formData.status<2"><icon-delete /></a-link>                      
                  </template>
           </a-table>
            </a-tab-pane>
            <a-tab-pane key="2" title="附件">
              <a-button type="primary" icon="download" style="margin-top: 10px;" @click="downloadAdd">附件上传</a-button>
              <div>
                <div v-for="(item,index) in upload.fileList" :key="item.id" style="display: flex;margin-top: 10px;justify-content: space-between;padding: 0 10px;background: #ddd;">
                  <div>{{item.filename || item.origin_name}}</div>
                  <div>类型：{{getDictData('dictObj','AttachmentType',item.attachable_type,2,columnsDist) }}</div>
                  <div>上传时间：{{item.created_at}}</div>
                  <div>
                    <a-link  title="下载" @click="downloadFile(item)"><icon-to-bottom /></a-link>
                    <a-link title="删除" @click="deleteDownload(index)"><icon-delete/></a-link>
                  </div>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-form>
        <template #footer> 
          <div style="display: flex; justify-content: space-between;align-items: center;">
            <div style="color: rgb(50 193 148);">
              <!-- tips：先选择"服务项目"后在操作明细,请按要求填写(导入)单据信息 -->
            </div>
            <div>
              <a-button @click="visible = false" style="margin-right: 20px;">关闭</a-button>
              <a-button type="primary" @click="handleBeforeOk(formRef)">
                保存
              </a-button>
            </div>
          </div>       
        </template>
      </a-drawer>
    <tray-list ref="trayListRef" @addClick="tableListPrant" v-if="visible"></tray-list>
    <file-type ref="filetypeRef" @addFile="addFileTap"/> 

</template>
<style>
   .form-top-main{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
   }
   .tab-main{
    display: flex;
    align-items: center;
    margin: 10px 0;
   }
   .tab-main .arco-form-item{
    margin-bottom: 0;
   }
   .tab-main .arco-switch{
    margin-right: 20px;
   }
</style>